import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../models/post_model.dart';
import '../../controller.dart';
import '../../../../../common/utils/toast_util.dart';
import '../../../../../common/utils/map_launcher_util.dart';
import '../../../../../common/api/comment_api.dart';
import '../../../../../common/api/friend_api.dart';
import '../../../../../common/services/user_service.dart';
import '../../../../../common/models/comment_models.dart';
import '../../../../../common/routers/names.dart';
import '../../../../../common/api/user_api.dart';
import '../../../../../common/utils/encryption_util.dart';
import '../../../../../common/services/http.dart';
import '../../../../../common/utils/permission_util.dart'; // 🎯 权限计算工具
import 'dart:developer' as developer;
import 'dart:convert';

class ReviewDetailBottomSheet extends StatefulWidget {
  // 详情数据
  final PostModel post;

  const ReviewDetailBottomSheet({
    Key? key,
    required this.post,
  }) : super(key: key);

  // 显示底部详情框的静态方法
  static Future<void> show({
    required PostModel post,
  }) {
    return Get.bottomSheet(
      // 使用 MediaQuery.removePadding 移除底部 padding
      MediaQuery.removePadding(
        context: Get.context!,
        removeBottom: true,
        child: ReviewDetailBottomSheet(
          post: post,
        ),
      ),
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true, // 允许内容滚动
      clipBehavior: Clip.antiAlias,
      enableDrag: true,
    );
  }

  @override
  State<ReviewDetailBottomSheet> createState() => _ReviewDetailBottomSheetState();
}

class _ReviewDetailBottomSheetState extends State<ReviewDetailBottomSheet> {
  bool isLiked = false;
  bool isDisliked = false;
  int likeCount = 0;
  int dislikeCount = 2;
  TextEditingController commentController = TextEditingController();
  final FocusNode _commentFocusNode = FocusNode();
  
  // 图片切换相关
  late PageController _imagePageController;
  int _currentImageIndex = 0;
  
  // 购物小票图片切换相关
  late PageController _receiptPageController;
  int _currentReceiptIndex = 0;
  
  // 🔥 真实评论回复数据（从API获取）
  List<Map<String, dynamic>> comments = [];
  
  // 发送状态控制
  bool _isSendingComment = false;
  
  // 点赞状态控制
  bool _isLiking = false;
  
  // 好友关系相关状态
  bool _isCheckingFriendship = true; // 是否正在检查好友关系
  bool _isFriend = false; // 是否已经是好友
  bool _isAddingFriend = false; // 是否正在发送好友申请
  
  // 🔥 新增：评论详情数据相关状态
  bool _isLoadingDetail = true; // 是否正在加载评论详情
  CommentDetailData? _commentDetail; // 从API获取的评论详情数据
  CommentUserData? _commentUser; // 从API获取的用户详情数据
  Map<String, dynamic>? _rawCommentData; // 🔥 保存原始评论数据以获取replies
  String? _detailErrorMessage; // 评论详情加载错误信息
  
  // 🔥 数据获取辅助方法（优先使用API数据，兜底使用PostModel数据）
  List<String> get _currentImages => _commentDetail?.commentImages.isNotEmpty == true 
      ? _commentDetail!.commentImages 
      : widget.post.images;
      
  List<String> get _currentShoppingImages => _commentDetail?.shoppingImages.isNotEmpty == true 
      ? _commentDetail!.shoppingImages 
      : widget.post.shoppingImages;
      
  String get _currentTitle => _commentDetail?.commentTitle.isNotEmpty == true 
      ? _commentDetail!.commentTitle 
      : widget.post.title;
      
  String get _currentAuthorName {
    // 优先使用API返回的用户数据，然后是评论中的发布者数据，最后是PostModel数据
    if (_commentUser?.username.isNotEmpty == true) {
      return _commentUser!.username;
    } else if (_commentDetail?.publisherNickname.isNotEmpty == true) {
      return _commentDetail!.publisherNickname;
    }
    return widget.post.authorName;
  }
      
  String get _currentAuthorAvatar {
    // 优先使用API返回的用户数据
    if (_commentUser?.userAvatarUrl.isNotEmpty == true) {
      return _commentUser!.userAvatarUrl;
    } else if (_commentDetail?.publisherAvatar.isNotEmpty == true) {
      return _commentDetail!.publisherAvatar;
    }
    return widget.post.authorAvatar;
  }
      
  String get _currentLocation => _commentDetail?.commentLocation.isNotEmpty == true 
      ? _commentDetail!.commentLocation 
      : '江苏省苏州市姑苏区金阊街道苏州市人民政府';
      
  String get _currentTimeAgo => _commentDetail?.commentPublishTime.isNotEmpty == true 
      ? _formatTimeAgo(_commentDetail!.commentPublishTime) 
      : widget.post.timeAgo;
  
  // 格式化时间显示 - 显示真实的绝对时间（包含年份）
  String _formatTimeAgo(String publishTime) {
    try {
      final DateTime publishDateTime = DateTime.parse(publishTime);
      
      // 🔥 显示真实的绝对时间，格式：yyyy-MM-dd HH:mm
      final String formattedTime = 
        '${publishDateTime.year}-'
        '${publishDateTime.month.toString().padLeft(2, '0')}-'
        '${publishDateTime.day.toString().padLeft(2, '0')} '
        '${publishDateTime.hour.toString().padLeft(2, '0')}:'
        '${publishDateTime.minute.toString().padLeft(2, '0')}';
      
      return formattedTime;
    } catch (e) {
      // 如果解析失败，尝试直接返回格式化的原始时间
      return publishTime.replaceAll('T', ' ').substring(0, publishTime.length > 16 ? 16 : publishTime.length);
    }
  }

  @override
  void initState() {
    super.initState();
    likeCount = widget.post.likeCount;
    _imagePageController = PageController();
    _receiptPageController = PageController();
    
    // 🔥 获取真实的评论详情数据
    _loadCommentDetail();
    
    // 检查好友关系
    _checkFriendRelationship();
  }


  


  /// 🔥 新增：加载评论详情数据
  Future<void> _loadCommentDetail() async {
    try {
      setState(() {
        _isLoadingDetail = true;
        _detailErrorMessage = null;
      });
      
      // 获取评论ID
      int commentId;
      try {
        if (widget.post.originalCommentId != null) {
          commentId = widget.post.originalCommentId!;
        } else {
          // 从字符串ID中解析数字
          final idParts = widget.post.id.split('_');
          if (idParts.length >= 3 && idParts[0] == 'real' && idParts[1] == 'comment') {
            commentId = int.parse(idParts[2]);
          } else {
            commentId = int.parse(widget.post.id);
          }
        }
      } catch (e) {
        developer.log('❌ 评论ID格式错误: ${widget.post.id}');
        setState(() {
          _isLoadingDetail = false;
          _detailErrorMessage = '评论ID格式错误';
        });
        return;
      }
      
      // 获取当前用户ID（如果已登录）
      final userService = UserService.to;
      final userId = userService.isLoggedIn ? userService.currentUser?.userid : null;
      
      developer.log('🔍 =============== 开始获取评论详情 ===============');
      developer.log('📝 评论ID: $commentId');
      developer.log('👤 当前用户ID: $userId');
      
      // 调用评论详情API
      final response = await CommentApi.getCommentDetail(
        commentId: commentId,
        userId: userId,
      );
      
      developer.log('📨 评论详情API响应: ${jsonEncode(response)}');
      
      if (response['status'] == 'success') {
        // 解析评论详情数据
        final commentDetailResponse = CommentDetailResponse.fromJson(response);
        
        if (commentDetailResponse.isSuccess && commentDetailResponse.data != null) {
          setState(() {
            _commentDetail = commentDetailResponse.data!;
            _commentUser = commentDetailResponse.user; // 🔥 保存用户数据
            _rawCommentData = response['comment']; // 🔥 保存原始评论数据
            _isLoadingDetail = false;
            
            // 更新UI状态
            likeCount = _commentDetail!.likeCount;
            isLiked = _commentDetail!.isLiked == 1;
            
            // 🔥 处理评论回复数据
            _processCommentReplies();
          });
          
          developer.log('✅ 评论详情获取成功！');
          developer.log('📊 评论详情：');
          developer.log('   标题: ${_commentDetail!.commentTitle}');
          developer.log('   内容: ${_commentDetail!.commentContent}');
          developer.log('   点赞数: ${_commentDetail!.likeCount}');
          developer.log('   发布者: ${_commentDetail!.publisherNickname}');
          developer.log('   图片数量: ${_commentDetail!.commentImages.length}');
          developer.log('   购物小票数量: ${_commentDetail!.shoppingImages.length}');
          
          // 🔥 输出用户详情信息
          if (_commentUser != null) {
            developer.log('📊 用户详情：');
            developer.log('   用户名: ${_commentUser!.username}');
            developer.log('   头像: ${_commentUser!.userAvatarUrl}');
            developer.log('   签名: ${_commentUser!.userSignature}');
            developer.log('   城市: ${_commentUser!.userCity}');
            developer.log('   积分: ${_commentUser!.userPoints}');
            developer.log('   标签: ${_commentUser!.userTags}');
          }
        } else {
          setState(() {
            _isLoadingDetail = false;
            _detailErrorMessage = commentDetailResponse.errorMessage;
          });
          developer.log('❌ 评论详情解析失败: ${commentDetailResponse.errorMessage}');
        }
      } else {
        final errorMsg = response['message'] ?? '获取评论详情失败';
        setState(() {
          _isLoadingDetail = false;
          _detailErrorMessage = errorMsg;
        });
        
        developer.log('❌ 评论详情API调用失败: $errorMsg');
        
        if (errorMsg.contains('评论不存在') || errorMsg.contains('已删除')) {
          ToastUtil.warning('💔 该评论已被删除或不存在');
        }
      }
      
    } catch (e, stackTrace) {
      developer.log('💥 获取评论详情异常: $e');
      developer.log('📍 异常堆栈: $stackTrace');
      
      setState(() {
        _isLoadingDetail = false;
        _detailErrorMessage = '获取评论详情失败: ${e.toString()}';
      });
      
      ToastUtil.error('获取评论详情失败');
    } finally {
      developer.log('🏁 =============== 评论详情获取完成 ===============');
    }
  }

  /// 🔥 处理评论回复数据
  void _processCommentReplies() {
    if (_rawCommentData?['replies'] != null && _rawCommentData!['replies'] is List) {
      final repliesData = _rawCommentData!['replies'] as List;
      
      if (repliesData.isNotEmpty) {
        comments.clear(); // 清空现有评论
        
        // 转换API回复数据为本地格式
        for (var reply in repliesData) {
          comments.add({
            'replyId': reply['replyId'],
            'avatar': reply['publisherAvatar'] ?? 'http://app.playtruly.cn/system/avatar.jpg',
            'username': reply['publisherNickname'] ?? '匿名用户',
            'content': reply['replyContent'] ?? '',
            'time': _formatReplyTime(reply['replyTime']),
            'likeCount': reply['likeCount'] ?? 0,
            'publisherId': reply['publisherId'],
          });
        }
        
        developer.log('🔄 评论回复数据已处理: ${comments.length}条回复');
        for (int i = 0; i < comments.length; i++) {
          final comment = comments[i];
          developer.log('   回复${i + 1}: ${comment['username']} - ${comment['content']}');
        }
      } else {
        developer.log('📝 replies数组为空');
      }
    } else {
      developer.log('📝 暂无评论回复数据');
    }
  }

  /// 格式化回复时间 - 显示真实的绝对时间（包含年份）
  String _formatReplyTime(String? replyTime) {
    if (replyTime == null || replyTime.isEmpty) return '未知时间';
    
    try {
      final DateTime replyDateTime = DateTime.parse(replyTime.replaceAll(' ', 'T'));
      
      // 🔥 显示真实的绝对时间，格式：yyyy-MM-dd HH:mm
      final String formattedTime = 
        '${replyDateTime.year}-'
        '${replyDateTime.month.toString().padLeft(2, '0')}-'
        '${replyDateTime.day.toString().padLeft(2, '0')} '
        '${replyDateTime.hour.toString().padLeft(2, '0')}:'
        '${replyDateTime.minute.toString().padLeft(2, '0')}';
      
      return formattedTime;
    } catch (e) {
      developer.log('⚠️ 时间格式解析失败: $replyTime');
      // 如果解析失败，尝试直接返回格式化的原始时间
      return replyTime.length > 16 ? replyTime.substring(0, 16) : replyTime;
    }
  }

  /// 跳转到用户信息页面（主评论发布者）- 🔥 学习活动详情页的实现
  void _navigateToUserInfo() async {
    try {
      // 获取发布者ID
      int publisherId;
      if (_commentUser?.userid != null) {
        publisherId = _commentUser!.userid;
      } else if (widget.post.authorId != null) {
        publisherId = widget.post.authorId!;
      } else {
        ToastUtil.error('无法获取用户信息');
        return;
      }
      
      developer.log('🎯 跳转到用户信息页面（主评论发布者）');
      developer.log('👤 开始获取用户信息，发布者ID: $publisherId');
      
      // 显示加载提示
      Get.dialog(
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
          ),
        ),
        barrierDismissible: false,
      );
      
      // 🔥 调用用户过滤内容API获取完整用户信息（学习活动详情页的实现）
      final userResponse = await UserApi.getUserFilteredContent(
        userId: publisherId,
        contentType: 'activities', // 先获取活动信息
      );
      
      // 关闭加载对话框
      Get.back();
      
      if (userResponse.isSuccess && userResponse.user != null) {
        final user = userResponse.user!;
        developer.log('✅ 成功获取用户信息: ${user.username}');
        
        // 🔥 将FilteredUserInfo转换为用户信息页面需要的参数（与活动详情页保持一致）
        final userInfo = {
          'userId': user.userid,
          'username': user.username,
          'avatar': user.userAvatarUrl ?? '',
          'signature': user.userSignature ?? '',
          'userLevel': user.userLevel ?? 0,
          'userFollowers': user.userFollowers ?? 0,
          'userLikes': user.userLikes ?? 0,
          'userPoints': user.userPoints ?? 0, // 🔥 添加积分字段支持（修复等级显示问题）
          'userTags': user.userTags ?? [],
          'userHobbies': user.userHobbies ?? [],
          'userFrequentPlaces': user.userFrequentPlaces ?? '未知',
          'userCity': user.userCity ?? '未知',
          'userImgUrls': user.userImgUrls ?? [],
          'activities': userResponse.activities ?? [], // 这里已经是 List<ActivityData>
          'friendCount': userResponse.friendCount ?? 0,
        };
        
        // 跳转到用户信息页面
        Get.toNamed(
          RouteNames.myUserInfo,
          arguments: userInfo,
        );
        
        developer.log('✅ 用户信息页面跳转完成');
      } else {
        developer.log('❌ 获取用户信息失败: ${userResponse.message}');
        ToastUtil.error('获取用户信息失败: ${userResponse.message ?? "未知错误"}');
      }
      
    } catch (e) {
      // 关闭可能的加载对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      developer.log('💥 获取用户信息异常: $e');
      ToastUtil.error('获取用户信息失败');
    }
  }

  /// 🗺️ 地图底部弹出框 - 打开外部地图应用
  void _openLocationInMap() {
    final location = _currentLocation;
    
    if (location.isEmpty || location == '江苏省苏州市姑苏区金阊街道苏州市人民政府') {
      ToastUtil.warning('位置信息不完整');
      return;
    }
    
    developer.log('🗺️ 评论详情页 - 准备显示地图底部弹出框');
    developer.log('📍 位置: $location');
    
    // 🎯 显示地图底部弹出框
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 🎨 顶部指示器
            Container(
              margin: const EdgeInsets.only(top: 8, bottom: 16),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            
            // 🎨 标题区域
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: const Color(0xFFE33641).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(
                      Icons.map,
                      color: Color(0xFFE33641),
                      size: 24,
                    ),
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      '打开地图',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 🎨 位置信息展示
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Row(
                children: [
                  Icon(Icons.location_on, color: Colors.grey[600], size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      location,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[700],
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            const SizedBox(height: 8),
            
            // 🗺️ 打开手机地图按钮
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () async {
                  Get.back(); // 关闭底部弹出框
                  await _openExternalMap();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFE33641),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(
                      Icons.launch_rounded,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      '打开手机地图',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 24),
            
            // 🎨 取消按钮
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              width: double.infinity,
              child: TextButton(
                onPressed: () => Get.back(),
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: Colors.grey[100],
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: const Text(
                  '取消',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey,
                  ),
                ),
              ),
            ),
            
            // 🎨 底部安全区域
            SizedBox(height: MediaQuery.of(Get.context!).padding.bottom + 16),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
    );
  }
  
  /// 🌍 打开外部地图应用
  Future<void> _openExternalMap() async {
    try {
      final location = _currentLocation;
      
      // 🔥 获取精确坐标
      double? apiLatitude;
      double? apiLongitude;
      
      // 🔥 从API获取的评论详情中提取坐标
      if (_rawCommentData != null) {
        try {
          final rawLat = _rawCommentData!['latitude'];
          final rawLng = _rawCommentData!['longitude'];
          
          if (rawLat != null && rawLng != null) {
            apiLatitude = (rawLat as num?)?.toDouble();
            apiLongitude = (rawLng as num?)?.toDouble();
            developer.log('✅ 成功从API获取精确坐标: $apiLatitude, $apiLongitude');
          }
        } catch (e) {
          developer.log('💥 提取API坐标异常: $e');
        }
      }
      
      // 🔥 如果API数据中没有坐标，尝试从PostModel中获取
      if ((apiLatitude == null || apiLongitude == null) && 
          (widget.post.latitude != null && widget.post.longitude != null)) {
        apiLatitude = widget.post.latitude;
        apiLongitude = widget.post.longitude;
      }
      
      final latitude = apiLatitude ?? 0.0;
      final longitude = apiLongitude ?? 0.0;
      
      developer.log('🌍 准备打开外部地图应用');
      developer.log('📍 位置: $location');
      developer.log('🌐 坐标: $latitude, $longitude');
      
      // 🚀 使用地图启动器工具类
      await MapLauncherUtil.openMapLocation(
        latitude: latitude,
        longitude: longitude,
        locationName: location,
        title: _currentTitle,
      );
      
    } catch (e) {
      developer.log('💥 打开外部地图失败: $e');
      ToastUtil.error('打开外部地图失败');
    }
  }
  


  /// 跳转到回复用户信息页面 - 🔥 学习活动详情页的实现
  void _navigateToReplyUserInfo(Map<String, dynamic> comment) async {
    try {
      // 获取回复用户ID
      final publisherId = comment['publisherId'] ?? 0;
      if (publisherId == 0) {
        ToastUtil.error('无法获取用户信息');
        return;
      }
      
      developer.log('🎯 跳转到用户信息页面（回复用户）');
      developer.log('👤 开始获取用户信息，回复用户ID: $publisherId');
      
      // 显示加载提示
      Get.dialog(
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
          ),
        ),
        barrierDismissible: false,
      );
      
      // 🔥 调用用户过滤内容API获取完整用户信息（学习活动详情页的实现）
      final userResponse = await UserApi.getUserFilteredContent(
        userId: publisherId,
        contentType: 'activities', // 先获取活动信息
      );
      
      // 关闭加载对话框
      Get.back();
      
      if (userResponse.isSuccess && userResponse.user != null) {
        final user = userResponse.user!;
        developer.log('✅ 成功获取用户信息: ${user.username}');
        
        // 🔥 将FilteredUserInfo转换为用户信息页面需要的参数（与活动详情页保持一致）
        final userInfo = {
          'userId': user.userid,
          'username': user.username,
          'avatar': user.userAvatarUrl ?? '',
          'signature': user.userSignature ?? '',
          'userLevel': user.userLevel ?? 0,
          'userFollowers': user.userFollowers ?? 0,
          'userLikes': user.userLikes ?? 0,
          'userPoints': user.userPoints ?? 0, // 🔥 添加积分字段支持（修复等级显示问题）
          'userTags': user.userTags ?? [],
          'userHobbies': user.userHobbies ?? [],
          'userFrequentPlaces': user.userFrequentPlaces ?? '未知',
          'userCity': user.userCity ?? '未知',
          'userImgUrls': user.userImgUrls ?? [],
          'activities': userResponse.activities ?? [], // 这里已经是 List<ActivityData>
          'friendCount': userResponse.friendCount ?? 0,
        };
        
        // 跳转到用户信息页面
        Get.toNamed(
          RouteNames.myUserInfo,
          arguments: userInfo,
        );
        
        developer.log('✅ 用户信息页面跳转完成');
      } else {
        developer.log('❌ 获取用户信息失败: ${userResponse.message}');
        ToastUtil.error('获取用户信息失败: ${userResponse.message ?? "未知错误"}');
      }
      
    } catch (e) {
      // 关闭可能的加载对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      developer.log('💥 获取用户信息异常: $e');
      ToastUtil.error('获取用户信息失败');
    }
  }

  @override
  void dispose() {
    commentController.dispose();
    _commentFocusNode.dispose();
    _imagePageController.dispose();
    _receiptPageController.dispose();
    super.dispose();
  }


  /// 检查好友关系
  Future<void> _checkFriendRelationship() async {
    try {
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      
      if (currentUser == null) {
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = false;
        });
        return;
      }
      
      // 🔥 优先使用API返回的用户数据中的userid，然后使用PostModel中的authorId
      int authorId;
      developer.log('🔍 调试数据来源:');
      developer.log('📝 评论ID: ${widget.post.id}');
      developer.log('📝 原始评论ID: ${widget.post.originalCommentId}');
      developer.log('📝 PostModel作者ID: ${widget.post.authorId}');
      developer.log('📝 API用户ID: ${_commentUser?.userid}');
      
      if (_commentUser?.userid != null) {
        // 🔥 优先使用API返回的用户数据
        authorId = _commentUser!.userid;
        developer.log('✅ 从API用户数据获取发布者ID: $authorId');
      } else if (widget.post.authorId != null) {
        // 兜底：使用PostModel中的authorId字段
        authorId = widget.post.authorId!;
        developer.log('✅ 从PostModel获取发布者ID: $authorId');
      } else {
        // 兜底：尝试从其他字段解析
        developer.log('⚠️ 无法获取发布者ID，无法检查好友关系');
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = false;
        });
        return;
      }
      
      // 如果是自己的评论，不需要检查好友关系
      if (authorId == currentUser.userid) {
        setState(() {
          _isCheckingFriendship = false;
          _isFriend = true; // 设为true以隐藏加好友按钮
        });
        return;
      }
      
      developer.log('🔍 开始检查好友关系');
      developer.log('👤 当前用户ID: ${currentUser.userid}');
      developer.log('👤 评论作者ID: $authorId');
      
      // 调用好友关系检查API
      final response = await FriendApi.checkFriendRelationship(
        userId: currentUser.userid,
        targetUserId: authorId,
      );
      
      if (response.isSuccess && response.data != null) {
        setState(() {
          _isFriend = response.data!.isFriend ?? false;
          _isCheckingFriendship = false;
        });
        
        developer.log('✅ 好友关系检查完成: ${_isFriend ? "已是好友" : "不是好友"}');
        developer.log('📊 好友关系详情:');
        developer.log('   - 关系类型: ${response.data!.relationshipType}');
        developer.log('   - 好友状态: ${response.data!.status}');
        developer.log('   - 是否好友: ${response.data!.isFriend}');
        developer.log('   - 好友关系ID: ${response.data!.friendshipId}');
      } else {
        setState(() {
          _isFriend = false;
          _isCheckingFriendship = false;
        });
        developer.log('⚠️ 好友关系检查失败: ${response.message}');
        developer.log('📊 响应状态: ${response.status}');
        developer.log('📊 响应数据: ${response.data}');
      }
      
    } catch (e) {
      developer.log('💥 检查好友关系异常: $e');
      setState(() {
        _isCheckingFriendship = false;
        _isFriend = false;
      });
    }
  }

  /// 发送好友申请
  Future<void> _addFriend() async {
    if (_isAddingFriend) return;
    
    try {
      setState(() {
        _isAddingFriend = true;
      });
      
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      // 获取发布者ID（与检查好友关系时的逻辑保持一致）
      int authorId;
      if (_commentUser?.userid != null) {
        // 🔥 优先使用API返回的用户数据
        authorId = _commentUser!.userid;
      } else if (widget.post.authorId != null) {
        // 兜底：使用PostModel中的authorId字段
        authorId = widget.post.authorId!;
      } else {
        ToastUtil.error('无法获取用户信息');
        return;
      }
      
      developer.log('🤝 开始发送好友申请');
      developer.log('👤 发送者ID: ${currentUser.userid}');
      developer.log('👤 接收者ID: $authorId');
      
      // 调用发送好友申请API
      final response = await FriendApi.sendFriendRequest(
        senderId: currentUser.userid,
        receiverId: authorId,
        message: '通过评论详情页发送的好友申请',
        free: PermissionUtil.calculateAddFriendFree(), // 🎯 动态计算加好友权限（模仿MyApplication2）
      );
      
      if (response.isSuccess) {
        // 🎯 增加加好友计数（模仿MyApplication2的逻辑）
        PermissionUtil.incrementAddFriendCount();
        
        ToastUtil.success('好友申请已发送！');
        developer.log('✅ 好友申请发送成功');
        
        // 发送成功后可以选择隐藏按钮或改变按钮状态
        // 这里我们重新检查好友关系状态
        await _checkFriendRelationship();
      } else {
        if (response.message.contains('已经是好友') || response.message.contains('你们已经是好友了')) {
          // 🔥 已经是好友的情况，更新UI状态并显示友好提示
          setState(() {
            _isFriend = true;
          });
          ToastUtil.info('你们已经是好友了');
          developer.log('ℹ️ 好友关系状态: 已经是好友');
        } else if (response.message.contains('已经发送过好友申请') || 
            response.message.contains('请等待对方处理')) {
          ToastUtil.info(response.message);
          developer.log('ℹ️ 好友申请状态: ${response.message}');
        } else {
          ToastUtil.error('发送失败: ${response.message}');
          developer.log('❌ 好友申请发送失败: ${response.message}');
        }
      }
      
    } catch (e) {
      developer.log('💥 发送好友申请异常: $e');
      ToastUtil.error('发送好友申请失败');
    } finally {
      setState(() {
        _isAddingFriend = false;
      });
    }
  }



  /// 处理点赞/取消点赞
  void _handleLike() async {
    // 检查是否已经在处理点赞请求
    if (_isLiking) {
      developer.log('⚠️ 点赞请求正在处理中，忽略重复点击');
      return;
    }
    
    // 检查用户是否登录
    final userService = UserService.to;
    if (!userService.isLoggedIn) {
      ToastUtil.warning('请先登录');
      return;
    }
    
    // 🔥 优先使用API获取的真实评论ID，兜底使用PostModel数据
    int commentId;
    if (_commentDetail?.commentId != null) {
      // 优先使用从API获取的真实评论ID
      commentId = _commentDetail!.commentId;
      developer.log('✅ 点赞使用API获取的评论ID: $commentId');
    } else if (widget.post.originalCommentId != null) {
      // 兜底1：使用PostModel中的originalCommentId
      commentId = widget.post.originalCommentId!;
      developer.log('⚠️ 点赞使用PostModel的originalCommentId: $commentId');
    } else {
      // 兜底2：从字符串ID中提取数字
      try {
        final idParts = widget.post.id.split('_');
        if (idParts.length >= 3 && idParts[0] == 'real' && idParts[1] == 'comment') {
          commentId = int.parse(idParts[2]);
        } else {
          commentId = int.parse(widget.post.id);
        }
        developer.log('⚠️ 点赞从PostModel.id解析的评论ID: $commentId');
      } catch (e) {
        developer.log('❌ 点赞评论ID解析失败: ${widget.post.id}');
        ToastUtil.error('评论ID格式错误');
        return;
      }
    }
    
    setState(() {
      _isLiking = true;
    });
    
    try {
      developer.log('');
      developer.log('👍 =============== 开始处理评论点赞 ===============');
      developer.log('🎯 评论ID: $commentId');
      developer.log('👤 用户ID: ${userService.currentUser?.userid}');
      developer.log('💖 当前点赞状态: ${isLiked ? "已点赞" : "未点赞"}');
      developer.log('📊 当前点赞数: $likeCount');
      
      // 调用点赞API
      final response = await CommentApi.likeComment(
        userId: userService.currentUser!.userid,
        commentId: commentId,
      );
      
      developer.log('📨 点赞API响应: ${jsonEncode(response)}');
      
      if (response['status'] == 'success') {
        final action = response['action'] ?? 'unknown';
        final pointsChange = response['pointsChange'] ?? 0;
        final message = response['message'] ?? '操作成功';
        
        // 根据服务器响应更新UI状态
        setState(() {
          if (action == 'like') {
            // 点赞成功
            if (!isLiked) {
              isLiked = true;
              likeCount += 1;
              // 如果之前是踩的状态，取消踩
              if (isDisliked) {
                isDisliked = false;
                dislikeCount = dislikeCount > 0 ? dislikeCount - 1 : 0;
              }
            }
            ToastUtil.success('👍 $message');
          } else if (action == 'unlike') {
            // 取消点赞成功
            if (isLiked) {
              isLiked = false;
              likeCount = likeCount > 0 ? likeCount - 1 : 0;
            }
            ToastUtil.info('已取消点赞');
          } else {
            // 其他情况，根据当前状态切换
            isLiked = !isLiked;
            likeCount += isLiked ? 1 : -1;
            if (likeCount < 0) likeCount = 0;
            ToastUtil.success(isLiked ? '👍 点赞成功' : '已取消点赞');
          }
        });
        
        if (pointsChange > 0) {
          developer.log('💰 获得积分: +$pointsChange');
          ToastUtil.info('获得积分: +$pointsChange');
          
          // 刷新用户积分信息
          userService.refreshUserInfo();
        }
        
        developer.log('✅ 点赞操作成功');
        developer.log('📊 更新后状态: ${isLiked ? "已点赞" : "未点赞"}, 点赞数: $likeCount');
        
      } else {
        // API调用失败
        final errorMsg = response['message'] ?? '点赞失败';
        developer.log('❌ 点赞操作失败: $errorMsg');
        
        if (errorMsg.contains('评论不存在') || errorMsg.contains('已删除')) {
          ToastUtil.error('💔 该评论已被删除');
        } else {
          ToastUtil.error('点赞失败: $errorMsg');
        }
      }
      
    } catch (e, stackTrace) {
      developer.log('💥 点赞操作异常: $e');
      developer.log('📍 异常堆栈: $stackTrace');
      ToastUtil.error('点赞异常: ${e.toString()}');
    } finally {
      setState(() {
        _isLiking = false;
      });
      
      developer.log('🏁 =============== 评论点赞处理完成 ===============');
      developer.log('');
    }
  }

  /// 发送评论回复
  void _sendComment() async {
    final text = commentController.text.trim();
    if (text.isEmpty) {
      ToastUtil.warning('请输入评论内容');
      return;
    }
    
    try {
      setState(() {
        _isSendingComment = true;
      });
      
      // 🔥 优先使用API获取的真实评论ID，兜底使用PostModel数据
      int commentId;
      if (_commentDetail?.commentId != null) {
        // 优先使用从API获取的真实评论ID
        commentId = _commentDetail!.commentId;
        developer.log('✅ 使用API获取的评论ID: $commentId');
      } else if (widget.post.originalCommentId != null) {
        // 兜底1：使用PostModel中的originalCommentId
        commentId = widget.post.originalCommentId!;
        developer.log('⚠️ 使用PostModel的originalCommentId: $commentId');
      } else {
        // 兜底2：从字符串ID中提取数字
        try {
          final idParts = widget.post.id.split('_');
          if (idParts.length >= 3 && idParts[0] == 'real' && idParts[1] == 'comment') {
            commentId = int.parse(idParts[2]);
          } else {
            commentId = int.parse(widget.post.id);
          }
          developer.log('⚠️ 从PostModel.id解析的评论ID: $commentId');
        } catch (e) {
          developer.log('❌ 评论ID解析失败: ${widget.post.id}');
          ToastUtil.error('评论ID格式错误');
          return;
        }
      }
      

      
      // 🔥 获取当前用户信息
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      developer.log('');
      developer.log('💬 =============== 开始发送评论回复 ===============');
      developer.log('🎯 使用的评论ID: $commentId');
      developer.log('👤 用户ID: ${currentUser.userid}');
      developer.log('👤 用户昵称: ${currentUser.username}');
      developer.log('👤 用户头像: ${currentUser.userAvatarUrl}');
      developer.log('📝 回复内容: $text');
      developer.log('📊 数据来源: ${_commentDetail != null ? "API评论详情" : "PostModel"}');
      
      // 🔥 调用API发送回复（使用真实的当前用户信息）
      final response = await CommentApi.addCommentReply(
        commentId: commentId,
        userId: currentUser.userid,
        userNickname: currentUser.username ?? '匿名用户',
        replyContent: text,
        userAvatarUrl: currentUser.userAvatarUrl ?? 'http://app.playtruly.cn/system/avatar.jpg',
      );
      
      if (response['status'] == 'success') {
        // 🔥 API调用成功，添加到本地评论列表（使用真实用户信息）
        setState(() {
          comments.add({
            'replyId': response['replyId'] ?? DateTime.now().millisecondsSinceEpoch,
            'avatar': currentUser.userAvatarUrl ?? 'http://app.playtruly.cn/system/avatar.jpg',
            'username': currentUser.username ?? '匿名用户',
            'content': text,
            'time': '刚刚',
            'likeCount': 0,
            'publisherId': currentUser.userid,
          });
        });
        
        // 清空输入框
        commentController.clear();
        
        // 移除焦点
        _commentFocusNode.unfocus();
        
        // 显示成功提示
        ToastUtil.success('评论发送成功');
        
        developer.log('✅ 评论回复发送成功');
        
        // 🔥 重新加载评论详情以获取最新的回复列表
        try {
          await _loadCommentDetail();
          developer.log('🔄 评论详情已重新加载，回复列表已更新');
        } catch (e) {
          developer.log('⚠️ 重新加载评论详情失败: $e');
        }
        
        // 刷新主评论列表
        try {
          final playsController = Get.find<PlaysController>();
          await playsController.refreshCommentData();
          developer.log('🔄 主评论列表已刷新');
        } catch (e) {
          developer.log('⚠️ 刷新主评论列表失败: $e');
          // 刷新失败不影响用户体验，只记录日志
        }
      } else {
        // API调用失败
        final errorMsg = response['message'] ?? '发送失败';
        
        developer.log('❌ 评论回复发送失败');
        developer.log('📊 失败详情:');
        developer.log('   - 评论ID: $commentId');
        developer.log('   - 错误信息: $errorMsg');
        developer.log('   - 完整响应: ${jsonEncode(response)}');
        
        // 根据错误类型给出不同提示
        if (errorMsg.contains('评论不存在') || errorMsg.contains('已删除')) {
          ToastUtil.error('💔 该评论已被删除，无法回复');
          developer.log('💡 建议: 尝试其他评论的回复功能，或联系管理员确认评论状态');
        } else if (errorMsg.contains('参数') || errorMsg.contains('格式')) {
          ToastUtil.error('参数错误: $errorMsg');
          developer.log('💡 建议: 检查传递的参数格式是否正确');
        } else {
          ToastUtil.error('发送失败: $errorMsg');
          developer.log('💡 建议: 检查网络连接或稍后重试');
        }
      }
      
    } catch (e, stackTrace) {
      developer.log('💥 发送评论异常: $e');
      developer.log('📍 异常堆栈: $stackTrace');
      ToastUtil.error('发送异常: ${e.toString()}');
    } finally {
      setState(() {
        _isSendingComment = false;
      });
      
      developer.log('🏁 =============== 评论回复处理完成 ===============');
      developer.log('');
    }
  }

  /// 提交评论举报（与MyApplication2保持一致的参数格式）
  Future<void> _submitCommentReport(String reportText, String selectedReason) async {
    try {
      developer.log('🚩 开始提交评论举报');
      developer.log('📝 举报内容: $reportText');
      developer.log('📝 选择原因: $selectedReason');
      
      // 获取当前用户
      final userService = UserService.to;
      final currentUser = userService.currentUser;
      if (currentUser == null) {
        ToastUtil.error('请先登录');
        return;
      }
      
      // 🔥 优先使用API获取的真实评论ID，兜底使用PostModel数据
      int commentId;
      if (_commentDetail?.commentId != null) {
        // 优先使用从API获取的真实评论ID
        commentId = _commentDetail!.commentId;
        developer.log('✅ 使用API获取的评论ID: $commentId');
      } else if (widget.post.originalCommentId != null) {
        // 兜底1：使用PostModel中的originalCommentId
        commentId = widget.post.originalCommentId!;
        developer.log('⚠️ 使用PostModel的originalCommentId: $commentId');
      } else {
        // 兜底2：从字符串ID中提取数字
        try {
          final idParts = widget.post.id.split('_');
          if (idParts.length >= 3 && idParts[0] == 'real' && idParts[1] == 'comment') {
            commentId = int.parse(idParts[2]);
          } else {
            commentId = int.parse(widget.post.id);
          }
          developer.log('⚠️ 从PostModel.id解析的评论ID: $commentId');
        } catch (e) {
          developer.log('❌ 评论ID解析失败: ${widget.post.id}');
          ToastUtil.error('评论ID格式错误');
          return;
        }
      }
      
      ToastUtil.info('正在提交举报...');
      
      // 🔥 使用与MyApplication2完全一致的参数格式
      final result = await _submitCommentReportWithMyApp2Format(
        reporterId: currentUser.userid,
        contentId: commentId,  // 评论ID
        reportReason: reportText, // 使用用户输入的完整内容
      );
      
      if (result['success'] == true) {
        developer.log('✅ 评论举报提交成功');
        ToastUtil.success('举报成功，我们会尽快处理');
      } else {
        developer.log('❌ 评论举报提交失败: ${result['message']}');
        ToastUtil.error('举报失败: ${result['message']}');
      }
      
    } catch (e) {
      developer.log('💥 提交评论举报异常: $e');
      ToastUtil.error('举报提交失败，请重试');
    }
  }

  /// 与MyApplication2保持一致的评论举报提交方法
  Future<Map<String, dynamic>> _submitCommentReportWithMyApp2Format({
    required int reporterId,
    required int contentId,
    required String reportReason,
  }) async {
    try {
      developer.log('🔄 =============== 开始举报评论（MyApplication2格式） ===============');
      developer.log('🎯 举报者ID: $reporterId');
      developer.log('🎯 评论ID: $contentId');
      developer.log('🎯 举报原因: $reportReason');

      // 🔥 构建与MyApplication2完全一致的请求参数
      final requestData = <String, dynamic>{
        'reportType': '评论',                    // 固定字符串 "评论"（与活动举报的区别）
        'reporterId': reporterId.toString(),    // 字符串格式的用户ID
        'contentId': contentId,                 // 评论ID
        'reportReason': reportReason,           // 举报内容
        'timestamp': DateTime.now().millisecondsSinceEpoch ~/ 1000, // 时间戳
      };

      developer.log('📊 请求参数（MyApplication2格式）: $requestData');
      
      // 🔥 使用AES加密（与MyApplication2保持一致）
      developer.log('🔐 开始AES加密评论举报数据...');
      
      // 使用 EncryptionUtil 创建加密载荷
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /reports/create/');

      // 发送请求
      final response = await HttpService.to.post(
        '/reports/create/',
        data: encryptedPayload,
      );

      developer.log('📨 评论举报响应: $response');

      // 检查响应状态
      if (response is Map<String, dynamic> && response['status'] == 'success') {
        developer.log('✅ 评论举报提交成功: ${response['message']}');
        return {
          'success': true,
          'message': response['message'] ?? '举报提交成功',
        };
      } else {
        String errorMessage = '举报提交失败';
        if (response is Map<String, dynamic> && response['message'] != null) {
          errorMessage = response['message'];
        }
        developer.log('❌ 评论举报提交失败: $errorMessage');
        return {
          'success': false,
          'message': errorMessage,
        };
      }

    } catch (e) {
      developer.log('💥 举报评论异常: $e');
      return {
        'success': false,
        'message': '举报提交失败: ${e.toString()}',
      };
    }
  }

  void _showReportDialog() {
    final TextEditingController reportController = TextEditingController();
    String selectedReason = '';
    
    Get.dialog(
      StatefulBuilder(
        builder: (context, setState) {
          return Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Container(
              padding: const EdgeInsets.all(20),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题
                  const Center(
                    child: Text(
                      '举报原因',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  
                  // 输入框
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextField(
                      controller: reportController,
                      maxLines: 4,
                      decoration: const InputDecoration(
                        hintText: '输入举报原因',
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  
                  // 预设选项
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: [
                      _buildReasonChip('爽约未到场', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('骂人', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('中途开溜', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('品行不端', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                      _buildReasonChip('吃的太多', selectedReason, (reason) {
                        setState(() {
                          selectedReason = reason;
                        });
                      }),
                    ],
                  ),
                  const SizedBox(height: 24),
                  
                  // 提交按钮
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () async {
                        String reportText = reportController.text.trim();
                        if (selectedReason.isNotEmpty) {
                          reportText = selectedReason + (reportText.isNotEmpty ? ': $reportText' : '');
                        }
                        
                        if (reportText.isNotEmpty) {
                          Get.back(); // 先关闭对话框
                          await _submitCommentReport(reportText, selectedReason);
                        } else {
                          ToastUtil.warning('请输入举报原因或选择预设选项');
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFFE33641),
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: const Text(
                        '提交举报信息',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildReasonChip(String reason, String selectedReason, Function(String) onTap) {
    bool isSelected = selectedReason == reason;
    return GestureDetector(
      onTap: () => onTap(reason),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFFE33641) : Colors.grey[200],
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          reason,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black87,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 使用MediaQuery安全地获取屏幕高度
    final screenHeight = MediaQuery.of(context).size.height;
    // 使用安全的计算方式，避免可能的NaN或Infinity
    final sheetHeight = screenHeight > 0 ? screenHeight * 0.9 : 500.0;
    
    return SizedBox(
      height: sheetHeight,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 🔥 加载状态指示器
          if (_isLoadingDetail)
            Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    '正在获取评论详情...',
                    style: TextStyle(color: Colors.grey[600], fontSize: 14),
                  ),
                ],
              ),
            ),
          
          // 🔥 错误状态提示
          if (!_isLoadingDetail && _detailErrorMessage != null)
            Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  Icon(Icons.warning_amber, color: Colors.orange, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '获取详情失败: $_detailErrorMessage，使用默认数据',
                      style: TextStyle(color: Colors.orange[700], fontSize: 12),
                    ),
                  ),
                ],
              ),
            ),
          
          // 主要内容区域
          Expanded(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 图片区域和用户信息 - 横向显示
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 图片 - 占据左侧主要空间（优先使用API数据）
                      if (_currentImages.isNotEmpty)
                        Expanded(
                          flex: 4,
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(12, 12, 0, 0),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(12),
                              child: AspectRatio(
                                aspectRatio: 1.2, // 🔥 统一使用1.2比例，避免拉伸
                                child: Stack(
                                  children: [
                                    // 图片切换区域
                                    PageView.builder(
                                      controller: _imagePageController,
                                      onPageChanged: (index) {
                                        setState(() {
                                          _currentImageIndex = index;
                                        });
                                      },
                                      itemCount: _currentImages.length,
                                      itemBuilder: (context, index) {
                                        return CachedNetworkImage(
                                          imageUrl: _currentImages[index],
                                          fit: BoxFit.cover,
                                          placeholder: (context, url) => Container(
                                            color: Colors.grey[50],
                                            // 移除loading动画，直接显示空白背景
                                          ),
                                          errorWidget: (context, url, error) => Container(
                                            color: Colors.grey[300],
                                            child: const Icon(Icons.image_not_supported, size: 50),
                                          ),
                                          // 缓存配置
                                          memCacheWidth: 600,
                                          memCacheHeight: 600,
                                          maxWidthDiskCache: 600,
                                          maxHeightDiskCache: 600,
                                        );
                                      },
                                    ),
                                    // 图片指示器
                                    if (_currentImages.length > 1)
                                      Positioned(
                                        bottom: 12,
                                        left: 0,
                                        right: 0,
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: _currentImages.asMap().entries.map((entry) {
                                            return GestureDetector(
                                              onTap: () {
                                                _imagePageController.animateToPage(
                                                  entry.key,
                                                  duration: const Duration(milliseconds: 300),
                                                  curve: Curves.ease,
                                                );
                                              },
                                              child: Container(
                                                width: 8.0,
                                                height: 8.0,
                                                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                                                decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  color: _currentImageIndex == entry.key
                                                      ? Colors.white
                                                      : Colors.white.withOpacity(0.4),
                                                  boxShadow: [
                                                    BoxShadow(
                                                      color: Colors.black.withOpacity(0.3),
                                                      blurRadius: 3,
                                                      offset: const Offset(0, 1),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            );
                                          }).toList(),
                                        ),
                                      ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      
                      // 用户信息 - 竖向显示在右侧
                      Container(
                        width: 80,
                        padding: const EdgeInsets.all(12.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                                                children: [
                        // 🔥 可点击的头像
                        GestureDetector(
                          onTap: _navigateToUserInfo,
                          child: ClipOval(
                            child: CachedNetworkImage(
                              imageUrl: _currentAuthorAvatar,
                              width: 50,
                              height: 50,
                              fit: BoxFit.cover,
                              placeholder: (context, url) => Container(
                                width: 50,
                                height: 50,
                                color: Colors.grey[200],
                                child: const Icon(Icons.person, size: 30, color: Colors.grey),
                              ),
                              errorWidget: (context, url, error) => Container(
                                width: 50,
                                height: 50,
                                color: Colors.grey[200],
                                child: const Icon(Icons.person, size: 30, color: Colors.grey),
                              ),
                              // 缓存配置
                              memCacheWidth: 100,
                              memCacheHeight: 100,
                              maxWidthDiskCache: 100,
                              maxHeightDiskCache: 100,
                            ),
                          ),
                        ),
                        const SizedBox(height: 8),
                            Text(
                              _currentAuthorName,
                              style: const TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: Colors.black,
                              ),
                            ),
                            const SizedBox(height: 6),
                            // 守护者标签
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                              decoration: BoxDecoration(
                                color: const Color(0xFFE33641),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: const Text(
                                '守护者',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 10,
                                ),
                              ),
                            ),
                            const SizedBox(height: 8),
                            // 加好友按钮 - 只有在不是好友时才显示
                            if (!_isFriend)
                              if (_isCheckingFriendship)
                                // 检查中显示加载指示器
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  child: SizedBox(
                                    width: 16,
                                    height: 16,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                        Color(0xFFE33641),
                                      ),
                                    ),
                                  ),
                                )
                              else
                                // 不是好友时显示加好友按钮
                                GestureDetector(
                                  onTap: _isAddingFriend ? null : _addFriend,
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    decoration: BoxDecoration(
                                      color: _isAddingFriend 
                                          ? Colors.grey[400] 
                                          : const Color(0xFFE33641),
                                      borderRadius: BorderRadius.circular(15),
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.black.withOpacity(0.1),
                                          blurRadius: 4,
                                          offset: const Offset(0, 2),
                                        ),
                                      ],
                                    ),
                                    child: _isAddingFriend
                                        ? SizedBox(
                                            width: 12,
                                            height: 12,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 2,
                                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                            ),
                                          )
                                        : const Text(
                                            '加好友',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 11,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                  ),
                                ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  
                  // 标题和按钮区域
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
                    child: Row(
                      children: [
                        // 标题
                        Expanded(
                          child: Text(
                            _currentTitle,
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 举报按钮
                        GestureDetector(
                          onTap: () {
                            _showReportDialog();
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: const Color(0xFFE33641),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: const Text(
                              '举报',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                              ),
                            ),
                          ),
                        ),

                        const SizedBox(width: 8),
                        // 点赞按钮
                        GestureDetector(
                          onTap: _isLiking ? null : _handleLike, // 🔥 调用真实的点赞API
                          child: Row(
                            children: [
                              _isLiking
                                  ? SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor: AlwaysStoppedAnimation<Color>(
                                          Color(0xFFE33641),
                                        ),
                                      ),
                                    )
                                  : Icon(
                                      isLiked ? Icons.thumb_up : Icons.thumb_up_outlined,
                                      color: isLiked ? const Color(0xFFE33641) : Colors.grey,
                                      size: 20,
                                    ),
                              const SizedBox(width: 4),
                              Text(
                                '$likeCount',
                                style: TextStyle(
                                  color: isLiked ? const Color(0xFFE33641) : Colors.grey,
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 不喜欢按钮
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              if (isLiked) {
                                isLiked = false;
                                likeCount--;
                              }
                              isDisliked = !isDisliked;
                              dislikeCount += isDisliked ? 1 : -1;
                            });
                          },
                          child: Row(
                            children: [
                              Icon(
                                isDisliked ? Icons.thumb_down : Icons.thumb_down_outlined,
                                color: isDisliked ? const Color(0xFFE33641) : Colors.grey,
                                size: 20,
                              ),
                              const SizedBox(width: 4),
                              Text(
                                '$dislikeCount',
                                style: TextStyle(
                                  color: isDisliked ? const Color(0xFFE33641) : Colors.grey,
                                  fontSize: 14,
                                ),
                              ),
                            ],
                          ),
                        ),
                     
                       
                      ],
                    ),
                  ),
                  
                  // 位置和时间信息 - 🗺️ 支持点击跳转地图
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: GestureDetector(
                      onTap: () => _openLocationInMap(), // 🗺️ 点击跳转到地图页面
                      child: Row(
                        children: [
                          Icon(
                            Icons.location_on, 
                            size: 16, 
                            color: _currentLocation.isNotEmpty && _currentLocation != '江苏省苏州市姑苏区金阊街道苏州市人民政府' 
                                ? const Color(0xFFE33641) // 🎨 有位置信息时显示红色，表示可点击
                                : Colors.grey
                          ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              _currentLocation,
                              style: TextStyle(
                                fontSize: 12,
                                color: _currentLocation.isNotEmpty && _currentLocation != '江苏省苏州市姑苏区金阊街道苏州市人民政府'
                                    ? const Color(0xFFE33641) // 🎨 有位置信息时显示红色，表示可点击
                                    : Colors.grey[600],
                                decoration: _currentLocation.isNotEmpty && _currentLocation != '江苏省苏州市姑苏区金阊街道苏州市人民政府'
                                    ? TextDecoration.underline // 🎨 添加下划线表示可点击
                                    : TextDecoration.none,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: Row(
                      children: [
                        const Icon(Icons.access_time, size: 16, color: Colors.grey),
                        const SizedBox(width: 4),
                        Text(
                          _currentTimeAgo,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  const Divider(height: 1, color: Color(0xFFF0F0F0)),
                  
                  // 🔥 评论区域标题和跟评输入框
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
                    child: Row(
                      children: [
                        const Text(
                          '评论',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            '${_rawCommentData?['total_replies'] ?? comments.length}条评论',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        ),
                        const Spacer(),
                        // 🔥 跟评输入框区域
                        Expanded(
                          child: Container(
                            margin: const EdgeInsets.only(left: 16),
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            decoration: BoxDecoration(
                              color: Colors.grey[200],
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Row(
                              children: [
                                Expanded(
                                  child: TextField(
                                    controller: commentController,
                                    focusNode: _commentFocusNode,
                                    decoration: const InputDecoration(
                                      hintText: '写评论...',
                                      border: InputBorder.none,
                                      hintStyle: TextStyle(color: Colors.grey, fontSize: 14),
                                      contentPadding: EdgeInsets.symmetric(vertical: 8),
                                    ),
                                    style: const TextStyle(fontSize: 14),
                                  ),
                                ),
                                const SizedBox(width: 8),
                                GestureDetector(
                                  onTap: _isSendingComment ? null : () => _sendComment(),
                                  child: Container(
                                    padding: const EdgeInsets.all(6),
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFE33641),
                                      borderRadius: BorderRadius.circular(15),
                                    ),
                                    child: _isSendingComment
                                        ? const SizedBox(
                                            width: 16,
                                            height: 16,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 2,
                                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                            ),
                                          )
                                        : const Icon(
                                            Icons.send,
                                            color: Colors.white,
                                            size: 16,
                                          ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 8),
                  
                  // 🔥 评论列表
                  _buildCommentList(),
                    
                  const Divider(height: 24),
                  
                  // 🔥 购物小票
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '购物小票',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 12),
                        if (_currentShoppingImages.isNotEmpty)
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 左侧图片区域 - 🔥 使用统一比例避免拉伸
                              Container(
                                width: 100,
                                height: 83, // 🔥 按1.2比例计算：100/1.2≈83
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(8),
                                  child: Stack(
                                    children: [
                                      // 购物小票图片切换
                                      PageView.builder(
                                        controller: _receiptPageController,
                                        onPageChanged: (index) {
                                          setState(() {
                                            _currentReceiptIndex = index;
                                          });
                                        },
                                        itemCount: _currentShoppingImages.length,
                                        itemBuilder: (context, index) {
                                          return CachedNetworkImage(
                                            imageUrl: _currentShoppingImages[index],
                                            fit: BoxFit.cover, // 🔥 保持比例填充，避免拉伸
                                            width: double.infinity,
                                            height: double.infinity,
                                            placeholder: (context, url) => Container(
                                              color: Colors.grey[50],
                                              // 移除loading动画，直接显示空白背景
                                            ),
                                            errorWidget: (context, url, error) => Container(
                                              color: Colors.grey[300],
                                              child: const Icon(Icons.image_not_supported),
                                            ),
                                            // 缓存配置
                                            memCacheWidth: 400,
                                            memCacheHeight: 400,
                                            maxWidthDiskCache: 400,
                                            maxHeightDiskCache: 400,
                                          );
                                        },
                                      ),
                                      // 购物小票图片指示器
                                      if (_currentShoppingImages.length > 1)
                                        Positioned(
                                          bottom: 6,
                                          left: 0,
                                          right: 0,
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: _currentShoppingImages.asMap().entries.map((entry) {
                                              return GestureDetector(
                                                onTap: () {
                                                  _receiptPageController.animateToPage(
                                                    entry.key,
                                                    duration: const Duration(milliseconds: 300),
                                                    curve: Curves.ease,
                                                  );
                                                },
                                                child: Container(
                                                  width: 5.0,
                                                  height: 5.0,
                                                  margin: const EdgeInsets.symmetric(horizontal: 2.0),
                                                  decoration: BoxDecoration(
                                                    shape: BoxShape.circle,
                                                    color: _currentReceiptIndex == entry.key
                                                        ? Colors.white
                                                        : Colors.white.withOpacity(0.4),
                                                    boxShadow: [
                                                      BoxShadow(
                                                        color: Colors.black.withOpacity(0.4),
                                                        blurRadius: 2,
                                                        offset: const Offset(0, 1),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              );
                                            }).toList(),
                                          ),
                                        ),
                                    ],
                                  ),
                                ),
                              ),
                              const SizedBox(width: 12),
                              // 右侧内容区域（可以添加描述信息）
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // 删除了购物小票描述文字
                                  ],
                                ),
                              ),
                            ],
                          )
                        else
                          // 如果没有购物小票，显示提示信息
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 20),
                            child: Center(
                              child: Text(
                                '暂无购物小票',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建评论列表
  Widget _buildCommentList() {
    if (comments.isEmpty) {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Center(
          child: Text(
            '暂无评论，快来抢沙发吧！',
            style: TextStyle(color: Colors.grey[400], fontSize: 14),
          ),
        ),
      );
    }
    
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: comments.length,
      itemBuilder: (context, index) {
        final comment = comments[index];
        return Container(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 🔥 可点击的回复用户头像
              GestureDetector(
                onTap: () => _navigateToReplyUserInfo(comment),
                child: ClipOval(
                  child: CachedNetworkImage(
                    imageUrl: comment['avatar'],
                    width: 36,
                    height: 36,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      width: 36,
                      height: 36,
                      color: Colors.grey[200],
                      child: const Icon(Icons.person, size: 20, color: Colors.grey),
                    ),
                    errorWidget: (context, url, error) => Container(
                      width: 36,
                      height: 36,
                      color: Colors.grey[200],
                      child: const Icon(Icons.person, size: 20, color: Colors.grey),
                    ),
                    // 缓存配置
                    memCacheWidth: 72,
                    memCacheHeight: 72,
                    maxWidthDiskCache: 72,
                    maxHeightDiskCache: 72,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              // 评论内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名
                    Text(
                      comment['username'],
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 2),
                    // 评论内容
                    Text(
                      comment['content'],
                      style: const TextStyle(
                        fontSize: 14,
                        color: Colors.black87,
                        height: 1.3,
                      ),
                    ),
                    const SizedBox(height: 4),
                    // 时间信息
                    Text(
                      comment['time'] ?? '未知时间',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[500],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}